<template>
    <div id="app-header" class="flex-between" style="-webkit-app-region: drag;-webkit-user-select: none;">
        <div class="app-logo flex-center" style="-webkit-app-region: no-drag;">
            <img class="logo-img" :src="logoSrc" alt="">
            <span class="separator"></span>
            <span class="schoolname">{{userInfo.schoolName}}</span>
            <div>
                <img v-if="isRedFlag === true" @click="showUpdate" class="newVersion" src="../../assets/img/home/newVersion.png" alt="" style="margin-left:20px;">
            </div>
            <div class="outline-tips flex-center" v-if="offlineLogo">
                <img class="outline-img" src="../../assets/img/home/outline.png" alt="" style="margin-right:5px;">
                <span class="s-14 outline-text">离线</span>
            </div>
        </div>
        <div class="app-handle flex-end" style="-webkit-app-region: no-drag;">
            <div class="personal-center flex-end">
                <div class="flex-center Platform pointer" @click="openPlatform">
                    <img src="../../assets/img/home/webOpen.png" alt="">
                    <span class="pointer">开放平台</span>
                </div>
                <el-dropdown  v-if="userInfo" class="mine"  @command="avatarCommand" trigger="click" >
                   <div class="flex-between pointer" @click="messageCenterIsShow = false">
                        <img class="pointer" v-if="userInfo.avatar" :src="userInfo.avatar" alt="">
                        <img class="pointer" v-else src="../../assets/img/home/mine.png" alt="">
                        <span class="pointer" >{{userInfo.name}}</span>
                    </div>
                    <el-dropdown-menu slot="dropdown" class="rightDropdown"  style="width: 90px;">
                        <el-dropdown-item :command="0">个人中心</el-dropdown-item>
                        <el-dropdown-item :command="1">
                            <div style="display:flex;" :style="toBeReadNum > 0  ? 'margin-left:7px' : ''" class="flex-center">
                                <div>系统通知</div>
                                <div v-if="toBeReadNum > 0" style="width: 7px;height: 7px;background: #F7931E;border: 1px solid #FFFFFF;border-radius: 50%;margin-left:2px"></div>
                            </div>
                        </el-dropdown-item>
                        <el-dropdown-item :command="2">意见反馈</el-dropdown-item>
                        <el-dropdown-item :command="3"><div :style="!isSign ? 'color:#a9a9a9' : ''">{{isSign ? '每日签到' : '已签到'}}</div></el-dropdown-item>
                        <el-dropdown-item :command="4">退出账号</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <div class="member-level">

                    <el-popover popper-class="mypoper" placement="bottom" :visible-arrow="true" width="200"
                        trigger="manual" :content="content" v-model="visiblePopver">
                        <div>
                            <i class="closePopver el-icon-close" @click="visiblePopver = false"></i>
                            <span style="font-weight: bold" v-if="vipMember === '2'">您的会员权益已到期</span>
                            <span v-else>
                                您的会员权益将于
                                <span style="font-weight: bold">
                                    {{this.content}}
                                </span>
                                过期
                            </span>
                        </div>
                        <div slot="reference" class="logo-icon" @click="ResetDB">
                            <img style="width: 38px;height: 16px;" v-if="vipMember === '0'" src="../../assets/img/person/svip.png" alt="">
                            <img style="width: 38px;height: 16px;" v-if="vipMember === '1'" src="../../assets/img/person/vip.png" alt="">
                            <img style="width: 38px;height: 16px;" v-if="vipMember === '2'" src="../../assets/img/person/nvip.png" alt="">
                        </div>
                    </el-popover>
                </div>
                <!-- <div class="message pointer" @click="showMessageCenter">
                    <div class="pointer">
                        <img src="../../assets/img/home/message-w.png" alt="">
                        <div class="message-tips" v-if="toBeReadNum && toBeReadNum > 0  ">
                            {{toBeReadNum?toBeReadNum:''}}
                        </div>
                    </div>
                </div> -->
            </div>
            <div class="win-tools flex-center">
                <div class="pointer" @click="toMini">
                    <img src="../../assets/img/home/mini-w.png" alt="">
                </div>
                <div class="pointer" @click="toMax">
                    <img src="../../assets/img/home/large-w.png" alt="" v-if="!isMax">
                    <img src="../../assets/img/home/normal-w.png" alt="" v-if="isMax">
                </div>
                <div class="pointer" @click="justLoginOut = false,close()">
                    <img src="../../assets/img/home/close-w.png" alt="">
                </div>
            </div>
            <div v-if="contorlOnce">
                <transition name="message">
                    <div class="message-center-container" v-show="messageCenterIsShow" @click.stop>
                        <message-center ref="messageCenter" :messageCenterIsShow.sync="messageCenterIsShow" 
                            :Type.sync="Type"
                            :toBeReadNum.sync="toBeReadNum"
                            ></message-center>
                    </div>
                </transition>
            </div>
        </div>

    </div>
</template>

<script>
import { SqlLib } from "../../../../../static/lib/sqlite/SqlLib";
import { SqlLibUser } from "../../../../../static/lib/sqlite/service/SqlLibUser";
import { UserResource } from "../../../../../static/lib/sqlite/model/UserResource";
import { VersionUpdater } from "../../../../../static/lib/downloader/VersionUpdater";
import { UpdateApp } from '../../utils/UpdateApp';
import messageCenter from '../../views/home/MessageCenter/MessageCenter'
import userApi from '../../api/user'
import { SqlLibBook } from '../../../../../static/lib/sqlite/service/SqlLibBook';
import { UUIDUtil } from '../../../../../static/utils/UUIDUtil';
import { collectClassTime } from '../../global/timer'
import { UserClassEvents } from '../../../../../static/lib/sqlite/model/UserClassEvents';
import moment from 'moment'
import { DownloadCenter } from '../../../../../static/lib/downloader/DownloadCenter';
import { collectUserPoint } from '../../api/point.js'
import { getAppNewVersion } from '@/content/api/appversion'
import bus from '../../assets/js/bus';
import store from '@/content/store/index.js'
import { mapMutations } from 'vuex';
const cryUtil = require('../../../../../static/utils/CrypUtil');
export default {
    // props: ['vipMember', 'userName',],
    components: { messageCenter },
    data () {
        return {
            toBeReadNum: 0,
            messageCenterIsShow: false,
            contorlOnce: false,
            vipMember: '2',
            isMax: false,
            offlineLogo: false,
            isPrimary: true,
            downloadTableData: [],
            visiblePopver: false,
            content: '',
            isSign: false,
            isRedFlag:false,
            versionData:[],
            Type:0,
            userInfo:[],
            justLoginOut:true,
        }
    },
    computed: {
        logoSrc () {
            if (this.isPrimary) {
                return require('../../assets/img/home/white-logo.png')
            } else {
                return require('../../assets/img/home/logo-ms.png')
            }
        },
    },
    mounted () {
        bus.$on('use-sign', (val) => {
            console.log('user-sign', val)
            this.isSign = val
        })
        //新一天更新积分系统
        this.updatePoint()
        bus.$on('set_versionData', (val) => {
            this.checkUpdate(val)
        })
        this.$nextTick(() => {
            this.initPersonStatus()
        })
        window.addEventListener('updateUserMessage', _ => {
            this.initPersonStatus()
        })
        window.addEventListener('updateLineStatus', e => {
            this.offlineLogo = e.detail
        })
        window.addEventListener('contorlMessageCenter', e => {
            this.contorlOnce = true
        })
    },
    methods: {
        ...mapMutations(['clearDownLoadCenter']),
        ResetDB(){
        },
        openPlatform(){
            var weburl = ''
            const shell = require('electron').shell;
            userApi.getWebAccessToken({
                // appKey:'NOVO_EDU_BEAUTY_SCIENCE_PC'
            }).then(res=>{
                if (res.code === '0') {
                    // return
                    console.log(res.returnValue.accessToken);
                    var baseUrl = process.env.NODE_ENV === 'production' ? 'https://'+res.returnValue.openWebDomain +'/jy/index.html#/?webToken=' :'https://'+res.returnValue.openWebDomain+'/jy/index.html#/?webToken='
                    weburl = baseUrl+res.returnValue.accessToken
                    shell.openExternal(weburl)
                }else{
                    weburl = process.env.NODE_ENV === 'production' ? 'https://'+res.returnValue.openWebDomain+'/jy/index.html#/' : 'https://'+res.returnValue.openWebDomain+'/jy/index.html#/'
                    shell.openExternal(weburl)
                }
            })
        },
        checkUpdate(data){
            if (data) {
                let oldVersion = this.$readIniFile('data', 'ver')
                var versionData = JSON.parse(data)
                console.log(versionData);
                this.versionData = versionData
                if (versionData.isRedFlag == '0' && oldVersion < versionData.currentVersion) {
                    this.isRedFlag = true
                }else{
                    this.isRedFlag = false
                }
            }
            // let oldVersion = this.$readIniFile('data', 'ver')
            // getAppNewVersion({
            //     clientType: '1',
            //     currentVersion:oldVersion,
            // }).then(res=>{
            //     console.log(res);
            //     if (res.code === '0') {
            //         this.versionData = res.returnValue
            //         if (res.returnValue.isRedFlag === '0' && oldVersion <res.returnValue.currentVersion) {
            //             this.isRedFlag = true
            //         }else{
            //             this.isRedFlag = false
            //         }
            //     }
            // })
        },
        async showUpdate(){
            let oldVersion = this.$readIniFile('data', 'ver')
            if (oldVersion < this.versionData.currentVersion){
                const path = require('path')
                let exePath = process.env.NODE_ENV === 'production' ? path.resolve(path.dirname(process.execPath), 'bos_updater.exe') : './bos_updater/bin/bos_updater'
                let exeParmsArr = [this.versionData.url,  this.versionData.isGlobal === '0' ? '/e' : '/z', '']
                UpdateApp.update(exePath, exeParmsArr, { message: this.versionData.description, version: this.versionData.currentVersion, close: false, cancel: '取消', }, false);
            }
        },
        initPersonStatus () {
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let user = SqlLibUser.queryCurrentUser(sqlLib);
            console.log(user)
            if (!user) {
                console.log('user为空')
                return
            }
            this.userInfo = user
            // console.log(this.userInfo.name.length);
            // var plat = document.getElementsByClassName('Platform')
            // var rightPosition = 282 + (this.userInfo.name.length - 3)*14
            // console.log(rightPosition);
            // plat.style.transform = translateX(-(rightPosition+'px'))
            this.isPrimary = this.$CONST.global.eduLevel.primary === user.eduLevelId
            this.vipMember = cryUtil.aesDecrypt(user.vipType, user.id, true);
            this.vipMember = new Buffer(this.vipMember, 'base64').toString('utf8');
            let remainderDays = new Buffer(cryUtil.aesDecrypt(user.remainderDays, user.id, true), 'base64').toString('utf8');
            if (parseInt(remainderDays) < 30) {
                let date = new Date()
                date.setDate(date.getDate() + parseInt(remainderDays))
                const forMaterDate = moment(date).format('YYYY-MM-DD')
                this.content = forMaterDate
                if (!this.memberWillPast) {
                    this.visiblePopver = this.memberWillPast = true
                    setTimeout(() => {
                        this.visiblePopver = false
                    }, 10000)
                }
            }
            //是否需要注册
            // this.isInformation = user.schoolId ? false : true;
            // this.offlineLogo = (localStorage.isOffline && localStorage.isOffline === "true");
        },
        avatarCommand(command){
            
            switch (command) {
                case 0:
                    this.messageCenterIsShow = false
                    this.$router.push('/index/person')
                    break
                case 1:
                    this.showMessageCenter(1)
                    break;
                case 2:
                    this.showFeedbackCenter(2)
                    break;
                case 3:
                    this.collectUserPoints()
                    break;
                case 4:
                    this.justLoginOut = true
                    this.close()
                    break;
                default:
                    break;
            }
        },
        showMessageCenter (val) {
            if (this.Type === 2) {
                this.Type = val
                this.messageCenterIsShow = true
            }else{
                this.Type = val
                this.messageCenterIsShow = !this.messageCenterIsShow
            }
            if (!this.contorlOnce) {
                this.contorlOnce = true
            }
            this.$nextTick(() => {
                this.$refs.messageCenter.scorllToBottom()
            })
        },
        showFeedbackCenter(val){
            if (this.Type === 1) {
                this.Type = val
                this.messageCenterIsShow = true
            }else{
                this.Type = val
                this.messageCenterIsShow = !this.messageCenterIsShow
            }
             if (!this.contorlOnce) {
                this.contorlOnce = true
            }
            this.$nextTick(() => {
                this.$refs.messageCenter.scorllToBottom()
            })
        },
        goPerson () {
            this.messageCenterIsShow = false
            this.$router.push('/index/person')
        },
        toMax () {
            this.messageCenterIsShow = false
            this.isMax = !this.isMax;
            if (this.isMax) {
                // console.log(this.$client);
                this.$client.fullScreen();
            } else {
                this.$client.miniWindow();
            }
        },
        toMini () {
            this.messageCenterIsShow = false
            this.$client.minimise();
        },
        close () {
            let closeTips = ''
            let downloadingTable = DownloadCenter.getInstance().getCurrentDownloadingLesson();
            if (downloadingTable.length === 0) {
                closeTips = '确认退出美丽科学吗？'
            } else {
                closeTips = '课程资源正在下载中，是否确认退出？'
            }
            this.messageCenterIsShow = false
            this.$dialog({
                confirm: '确认',
                cancel: '取消',
                message: closeTips,
                close: false,
                type: "warn"
            }).then(() => {
                if (this.justLoginOut) {
                    this.$electron.ipcRenderer.send('close-all-res')
                    //先暂停下载中心的所有下载器
                    DownloadCenter.getInstance().pauseAlldownloader();
                    //移除下载中心单例
                    DownloadCenter.removeInstance();
                    this.clearDownLoadCenter()
                    localStorage.removeItem("isOffline");
                    userApi.loginOut({}).then(response => {
                        // clearInterval(window.postMessageInterval)
                        // window.netStatus = false
                        localStorage.removeItem("accesstoken");
                        localStorage.removeItem("refreshToken");
                        this.$router.push({ name: 'login' });
                    }).catch(error => {
                        // clearInterval(window.postMessageInterval)
                        // window.netStatus = false
                        localStorage.removeItem("accesstoken");
                        localStorage.removeItem("refreshToken");
                        this.$router.push({ name: 'login' });
                    });
                    this.$electron.ipcRenderer.send('hideSuspensionWindow')
                    return
                }
                this.insetClassTime()
                let versionUpdate = new VersionUpdater();
                if (versionUpdate.isRequireRefresh()) {//如果当前正在进行资源升级，要取消之前同步的所有DB数据
                    let sqlLib = SqlLib.getInstance(window.$DBDIR);
                    let user = SqlLibUser.queryCurrentUser(sqlLib);
                    let userResource = new UserResource();
                    userResource.userId = user.id;
                    sqlLib.deleteObjectByKey(userResource, "userId");
                }
                if (localStorage.isSilent) {
                    let params = JSON.parse(localStorage.isSilent)
                    console.log(params.exePath, params.exeParmsArr, params.message)
                    UpdateApp.update(params.exePath, params.exeParmsArr, params.message)
                }
                localStorage.removeItem('isOffline');
                this.$client.closeAllWindow();
            })
        },
        insetClassTime () {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let user = SqlLibUser.queryCurrentUser(sqlLib)
            let classEndEvent = new UserClassEvents()
            classEndEvent.id = UUIDUtil.uuid()
            classEndEvent.type = '1'
            classEndEvent.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
            classEndEvent.userId = user.id
            SqlLibBook.insertEndClassTime(sqlLib, classEndEvent)
            collectClassTime()
            // collectClassTime().then(res=>{
            //     if(res.code==='0'){
            //         SqlLibBook.clearEventsTableAndClassTimeTable(sqlLib)
            //     }
            // })
        },
        async collectUserPoints () {
            if (localStorage.getItem('isOffline') === 'true') {
                this.$message.error('您当前处于离线模式，无法签到')
                return
            }
            if (!this.isSign){
                this.$message.warning('每日只可签到一次') 
                return //已签到后直接return 不提示
            } 
            // if (!this.isSign) {
            //     this.$message.warning('每日只可以签到一次')//已签到时弹出提示框
            //     return
            // } 
            const res = await collectUserPoint({ channel: 0  })
            console.log(res);
            if (res) {
                if (res.code === '0') {
                    // console.log(res.message);
                    this.$message.success('签到成功')
                }
                if (res.code === '-49' || res.code === '-1') {
                    this.$message.warning('每日只可签到一次')
                }
            }
            
            this.isSign = false
        },
        updatePoint () {
            localStorage.removeItem('point')
            localStorage.setItem('point', JSON.stringify([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11]))
            // let sqlLib = SqlLib.getInstance(window.$DBDIR);
            // let user = SqlLibUser.queryCurrentUser(sqlLib);
            // const pointTime = localStorage.getItem('pointTime') ? JSON.parse(localStorage.getItem('pointTime')) : ''

            // if (pointTime && pointTime[user.id]) {
            //     const date = new Date(pointTime[user.id])
            //     const newDate = new Date()
            //     if (date.getDate() !== newDate.getDate() && date.getMonth !== newDate.getMonth()) {
            //         this.showsingIn = true
            //     }
            // } else {
            //     localStorage.setItem('pointTime', JSON.stringify({ [user.id]: new Date() }))
            //     localStorage.setItem('point', JSON.stringify([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
            //     this.showsingIn = true
            // }
        }

    }
}
</script>

<style lang="scss">
.closePopver {
    position: absolute;
    top: 3px;
    right: 6px;
    margin-bottom: 10px;
    display: inline-block;
    font-size: 15px;
    cursor: pointer;
}
.mypoper {
    width: auto !important;
    min-width: 150px !important;
}
.el-popover {
    font-size: 12px !important;
    &::before {
        content: "";
        position: absolute;
        top: 0;
        right: 50%;
        border-bottom: 5px solid #fff;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
    }
}
.el-popover--plain {
    padding: 3px 10px !important;
    padding-right: 25px !important;
}
#app-header {
    position: relative;
    width: 100vw;
    height: 64px;
    background: url(../../assets/img/home/header-bg.png);
    background-size: cover;
    .schoolname {
        color: #dceeff;
        // padding-left: 14px;
        // margin-left: 14px;
        // display: inline-block;
        // border-left: 1px solid #dceeff;
    }
    .newVersion{
        cursor:pointer
    }
    .outline-tips {
        margin-left: 20px;
        width: 54px;
        height: 21px;
        background: #E0E8EE;
        border-radius: 2px;
        .outline-img {
            width: 14px;
            height: 14px;
            margin-top: 1px;
        }
        .outline-text{
            font-size: 14px;
            font-weight: 400;
            color: #979797;
            transform: translateX(-2px);
        }
    }
    .message-center-container {
        position: absolute;
        right: 5px;
        height: 735px;
        width: 360px;
        opacity: 1;
        z-index: 3333;
        top: 74px;
        transition: all 0.5s ease-in-out;
        // transform: translateX(30%);
    }
    @media screen and(max-height: 800px) {
        .message-center-container {
            right: -6vw;
            top: 9vh;
        }
    }
    // .hidden-message-center {
    //     height: 0;
    //     width: 0;
    //     opacity: 0;
    // }
    .message-enter-active,
    .message-leave-active {
        transition: all 0.8s ease-in-out;
    }
    .message-enter,
    .message-leave-to {
        opacity: 0;
        height: 0;
        width: 0;
    }
    .app-logo {
        height: 100%;
        .logo-img {
            height: 40px;
            margin-left: 26px;
        }
        .separator {
            display: inline-block;
            width: 1px;
            height: 14px;
            background-color: rgba(209, 219, 226, 1);
            margin: 0  17px;
        }
    }
    .logo-icon{
        margin-top: -7px;
        transform: translateX(-15px);
    }
    .personal-center {
        .sign_box{
            position: absolute;
            top: 22px;
            right: 427px;
            color: #fff;
            font-size: 14px;
            font-weight: 400;
            -webkit-app-region: no-drag;
        }
        .Platform{
            // position: absolute;
            // top: 22px;
            // right: 282px;
            margin-right: 24px;
            color: #fff;
            font-size: 14px;
            font-weight: 400;
            -webkit-app-region: no-drag;
            transform: translateY(-2px);
            img{
                width: 18px;
                height: 18px;
                margin-right: 8px;
            }
        }
        .sign{
            width: 55px;
            height: 22px;
        }
        .news{
            position: absolute;
            top: 22px;
            right: 350px;
            color: #fff;
            -webkit-app-region: no-drag;
        }
        .feedback{
            position: absolute;
            top: 22px;
            right: 274px;
            color: #fff;
            -webkit-app-region: no-drag;
        }
        .mine{
            // position: absolute;
            // top: 22px;
            // right: 201px;
            margin-right: 24px;
            font-size: 14px;
            color: #fff;
            transform: translateY(-2px);
            -webkit-app-region: no-drag;
            img{
                width: 25px;
                height: 25px;
                margin-right: 8px;
                border-radius: 50%;
                border: 2px solid #FFFFFF;
            }
        }
        .member-level {
            // position: absolute;
            // top: 25px;
            // right: 135px;
        }
        .message {
            margin-left: 16px;
            margin-top: 2px;
            position: relative;
            .message-tips {
                position: absolute;
                width: 28px;
                height: 28px;
                color: #fff;
                line-height: 28px;
                text-align: center;
                top: -12px;
                right: -12px;
                font-size: 14px;
                transform: scale(0.5, 0.5);
                border-radius: 50%;
                background: #f56c6b;
            }
            img {
                width: 20px;
                height: 18px;
            }
        }
    }
    .win-tools {
        line-height: 0;
        margin-left: 30px;
        div {
            margin-right: 20px;
        }
        img {
            width: 14px;
            height: 14px;
        }
    }
}
@media screen and(max-width:1439px) {
    #app-header {
        height: 50px;
        .app-logo {
            transform: scale(0.8, 0.8);
            .logo-img {
                margin-left: 10px;
            }
        }
        .personal-center {
            transform: scale(0.8, 0.8);
        }
        .win-tools {
            margin-left: 15px;
        }
    }
}
</style>

<style lang="scss" scope>
.el-dropdown-menu{
    padding: 6px 0px;
    border-radius: 4px !important;
    // margin: 0 !important;
    // transform: translateX(20px);
    // margin-left: 10px !important;
    box-shadow: 2px 1px 9px 0px rgba(0,0,0,0.15) !important;;
    .el-dropdown-menu__item{
        color: #606266 !important;
        width: calc(100% - 8px);
        border-radius: 2px !important;
    }
    .el-dropdown-menu__item:focus, .el-dropdown-menu__item:not(.is-disabled):hover{
        background-color:#E8F3FF !important ;
    }
}
</style>